# -*- coding: utf-8 -*-
# @File : config_loader.py.PY
# @Author : tang1jun
# @Time : 2025/04/16 0016 15:25:09

"""
@author: zhangyu
@contact: <EMAIL>
@software: PyCharm
@file: config_loader.py
@time: 2021/1/26 10:32 上午
"""

import logging
import os
import json

from pathlib import Path
from typing import Dict, Any

from addon.configs.config_switch import environment


class ConfigLoader:
    """多环境配置加载器"""

    def __init__(self, env: str = None):
        self.config_dir = Path(__file__).parent
        self.env = env or os.getenv("APP_ENV", "development")
        self._config = self._load_config()

    def _load_config(self) -> Dict[str, Any]:
        """加载并合并配置"""
        # 加载基础配置
        base_config = self._read_json("base.json")

        # 加载环境特定配置
        env_config = self._read_json(f"{self.env}.json")

        # 递归合并字典
        return self._deep_merge(base_config, env_config)

    # === 读取json配置文件 ===
    def _read_json(self, filename: str) -> Dict[str, Any]:
        """ 读取json配置文件 """
        try:
            with open(self.config_dir / filename, 'r', encoding='utf-8') as file:
                return json.load(file) or {}
        except Exception as e:
            logging.error(f"配置文件加载失败: {str(e)}")
            return {}

    def _deep_merge(self, base: Dict, update: Dict) -> Dict:
        """深度合并两个字典"""
        for key, val in update.items():
            if isinstance(val, dict) and key in base:
                base[key] = self._deep_merge(base[key], val)
            else:
                base[key] = val
        return base

    def get(self, key: str, default: Any = None) -> Any:
        """获取配置项"""
        keys = key.split('.')
        value = self._config
        for k in keys:
            value = value.get(k)
            if value is None:
                return default
        return value


if environment == 'production':
    config = ConfigLoader('production')
elif environment == 'test':
    config = ConfigLoader('test')
else:
    config = ConfigLoader('development')
